package com.imooc.article.controller;

import com.imooc.api.config.RabbitMQConfig;
import com.imooc.api.config.RabbitMQDelayConfig;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 *
 * @auther Levi
 * @Date: 2021/03/22/13:50
 * @Description:
 */
@RestController
@RequestMapping("producer")
public class RabbitMQController {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("/hello")
    public Object hello() {
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_ARTICLE,
                                       "article.do",
                                        "hello rabbitMQ!!");
        return "hello";
    }


    @RequestMapping("/delay")
    public Object delay() {

        MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //设置持久化
                message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                //设置延迟的时间 ms  毫秒
                message.getMessageProperties().setDelay(5000);
                return message;
            }
        };

        rabbitTemplate.convertAndSend(RabbitMQDelayConfig.EXCHANGE_DELAY,
                "delay.demo",
                "这是一条延迟消息~~~~",
                messagePostProcessor
        );
        System.out.println("生产者发送消息时间: "+new Date());
        return "hello";
    }

}
